import qrcode
import sys
from PIL import Image, ImageDraw, ImageFont


def mpix(v, dpi=300):
    return int(v * (dpi / 25.4))


if __name__ == "__main__":
    cl = sys.argv[1]
    cln = sys.argv[2]
    num = sys.argv[3]
    subdir = sys.argv[4]

    w = 100
    code = "TX-%s%s-%s" % (cl, cln.rjust(3, '0'), num.rjust(3, '0'))

    h = w * 0.618

    color = (0, 0, 0)
    n = int(cln)

    if cl == "R":
        if n == 8:
            color = (n, 70, 90)
        else:
            color = (n, 0, 0)
    elif cl == "G":
        if n == 8:
            color = (70, n, 90)
        else:
            color = (0, n, 0)
    elif cl == "B":
        if n == 8:
            color = (70, 90, n)
        else:
            color = (0, 0, n)
    else:
        print("error input")
        exit(1)

    bg = Image.new('RGB', (mpix(w), mpix(h)), color=color)

    qr = qrcode.QRCode(box_size=16, border=2)

    fill_color = "black"
    back_color = "white"
    if n < 200:
        fill_color = "white"
        back_color = "black"

    qr.add_data(code)
    qr.make(fit=True)
    qr_img = qr.make_image(fill_color=fill_color, back_color=back_color)

    bg_w, bg_h = bg.size
    qr_w, qr_h = qr_img.size

    q_x = bg_w - qr_w - mpix(10)
    q_y = int((bg_h - qr_h) * 3 / 4)

    bg.paste(qr_img, (q_x, q_y))

    draw = ImageDraw.Draw(bg)

    f_x = mpix(8)
    f_y = mpix(2)

    fill = "black"
    if n < 200:
        fill = "white"

    font = ImageFont.truetype("hb.ttf", size=85)
    draw.text((f_x, f_y), code, fill=fill, font=font)

    bg.save("./img/%s/%s.png" % (subdir, code))
